import {Injectable} from '@nestjs/common';
// ORM
import {InjectRepository} from '@nestjs/typeorm';
import {Repository, UpdateResult} from 'typeorm';
import {ApplyFlyerEntity} from '../entity/apply.flyer.entity';
import {ApplyFlyerDto} from '../dto/apply.flyer.dto';
import {ApplyUserStatus} from "../common/constants";

@Injectable()
export class ApplyFlyerService {
    constructor(
        @InjectRepository(ApplyFlyerEntity)
        private readonly applyFlyerRepository: Repository<ApplyFlyerEntity>,
    ) {
    }

    async createOne(applyUserDto: ApplyFlyerDto): Promise<ApplyFlyerEntity> {
        return await this.applyFlyerRepository.save(applyUserDto);
    }

    async editOne(applyUserDto: ApplyFlyerDto): Promise<UpdateResult> {
        return await this.applyFlyerRepository.update({id: applyUserDto.id}, applyUserDto);
    }

    async delOne(id: string): Promise<UpdateResult> {
        return await this.applyFlyerRepository.update({id}, {status: ApplyUserStatus.DELETED});
    }

    async getOneById(id: string): Promise<ApplyFlyerEntity> {
        const qb = this.applyFlyerRepository.createQueryBuilder();
        qb.where({id})
        return qb.getOne()
    }

    async getOneByAccountId(accountId: string): Promise<ApplyFlyerEntity> {
        const qb = this.applyFlyerRepository.createQueryBuilder();
        qb.where({accountId})
        return qb.getOne()
    }

    async getAll(status?: ApplyUserStatus): Promise<ApplyFlyerEntity[]> {
        const qb = this.applyFlyerRepository.createQueryBuilder();
        if (status) {
            qb.where({status})
        }
        return qb.getMany()
    }
}
